package com.atstudy.dao;

import com.atstudy.entites.Account;
import com.atstudy.utils.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/1/31 9:26
 * @copyright: 博为峰
 */
public class AccountDaoImpl implements AccountDao {
    @Override
    public Account selectAccountById(int id) {
        Account account = null;
        Connection conn = null;
        try {
            conn = DBUtil.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement("select * from account where id = ?");
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                int aid = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int balance = resultSet.getInt("balance");
                account = new Account();
                account.setId(aid);
                account.setName(name);
                account.setBalance(balance);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                DBUtil.closeConn(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return account;
    }

    @Override
    public List<Account> selectAccount() {
        Connection conn = null;
        List<Account> list = new ArrayList<>();
        try {
            conn = DBUtil.getConn();
            PreparedStatement preparedStatement = conn.prepareStatement("select * from account");
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                list.add(new Account(resultSet.getInt("id"), resultSet.getString("name"),
                        resultSet.getInt("balance")));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            try {
                DBUtil.closeConn(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return list;
    }
}
